// tts.js - 更新可用音色与模型映射

import { ipcMain } from 'electron'
import { textToSpeech, translateText, batchTranslate } from '../api/openaiTtsService'
import { google_textToSpeech, listVoices, speechToText } from '../api/googleTTS'
import { ensureConfigInitialized, serviceUrl } from '../config/config'

const MODEL_NAME = 'tts'

/**
 * 获取特定模型支持的语音列表
 * @param {string} modelId - 模型ID
 * @returns {Array} 该模型支持的语音列表
 */
export async function getAvailableVoices(modelId = null) {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort
  try {
    const response = await fetch(`${http_url}/apis/voice/api/tts/voices/${modelId}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (data.code !== 200) {
      throw new Error(`API error! message: ${data.message}`);
    }
    return data.data;
  } catch (error) {
    console.error('获取模型支持的语音失败:', error);
    throw error;
  }
}

/**
 * 获取所有可用的语音
 * @returns {Promise<Array>} 语音列表
 */
export async function getAllVoices() {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort
  try {
    const response = await fetch(`${http_url}/apis/voice/api/tts/voices`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (data.code !== 200) {
      throw new Error(`API error! message: ${data.message}`);
    }
    return data.data;
  } catch (error) {
    console.error('获取所有语音失败:', error);
    throw error;
  }
}

/**
 * 获取google的语音列表
 */
async function getGoogleAllVoices() {
  return await listVoices();
}

/**
 * 获取可用的TTS模型列表
 * @returns {Array} 可用模型列表
 */
export const getAvailableTtsModels = async () => {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort
  try {
    const response = await fetch(`${http_url}/apis/voice/api/tts/models`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data.code);
    if (data.code !== 200) {
      throw new Error(`API error! message: ${data.message}`);
    }
    return data.data;
  } catch (error) {
    console.error('获取TTS模型失败:', error);
    throw error;
  }
};

/**
 * 获取语音指令模板列表
 * @returns {Array} 语音指令模板列表
 */
export const getVoiceInstructionTemplates = async () => {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort
  console.log("获取语音指令模板");
  try {
    const response = await fetch(`${http_url}/apis/voice/api/tts/templates`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (data.code !== 200) {
      throw new Error(`API error! message: ${data.message}`);
    }
    return data.data;
  } catch (error) {
    console.error('获取语音指令模板失败:', error);
    throw error;
  }
};

/**
 * 获取所有支持的语言
 * @returns {Promise<Array>} 语言列表
 */
export async function getSupportedLanguages() {
  // 确保配置初始化完成
  await ensureConfigInitialized();

  const http_url = serviceUrl.baseUrlWithPort
  console.log("获取所有支持的语言");
  try {
    const response = await fetch(`${http_url}/apis/voice/api/tts/languages`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    if (data.code !== 200) {
      throw new Error(`API error! message: ${data.message}`);
    }
    return data.data;
  } catch (error) {
    console.error('获取语言列表失败:', error);
    throw error;
  }
}

export async function synthesize (text, model, voice, language, instructions) {
  try {
    console.log("监听到tts/synthesize方法")

    return await textToSpeech(text, model, voice, language, instructions);
  } catch (error) {
    console.error('TTS合成请求处理失败:', error);
    throw error;
  }
}

export async function textTranslate (text, sourceLang, targetLang) {
  try {
    console.log("监听到tts/textTranslate方法")

    return await translateText(text, sourceLang, targetLang);
  } catch (error) {
    console.error('翻译请求处理失败:', error);
    throw error;
  }
}

export async function batchTextTranslate (items, targetLang) {
  try {
    console.log("监听到tts/batchTextTranslate方法")

    return await batchTranslate(items, targetLang);
  } catch (error) {
    console.error('批量翻译请求处理失败:', error);
    throw error;
  }
}

export async function synthesize_google_textToSpeech (text, languageCode = 'zh-CN', ssmlGender = 'NEUTRAL', name, speakingRate = 1.0) {
  try {
    console.log("监听到tts/synthesize_google_textToSpeech方法")

    return await google_textToSpeech(text, languageCode, ssmlGender, name, speakingRate);
  } catch (error) {
    console.error('googleTTS合成请求处理失败:', error);
    throw error;
  }
}

export async function speechToTextWithGoogle(audioFilePath, language = 'zh', outputFormat = 'srt', outputDir = null, scriptContent = null){
  return await speechToText(audioFilePath, language, outputFormat, outputDir, scriptContent)
}

/**
 * 注册TTS相关的IPC处理器
 */
export function init() {
  // 获取可用的语音模型
  ipcMain.handle(MODEL_NAME + '/getVoices', async (event, modelId) => {
    return getAvailableVoices(modelId)
  });

  // 获取可用的语音模型
  ipcMain.handle(MODEL_NAME + '/getAllVoices', async () => {
    return getAllVoices();
  });

  // 音转文
  ipcMain.handle(MODEL_NAME + '/speechToTextWithGoogle', async (event, ...args) =>  {
    return speechToTextWithGoogle(...args);
  });

  // 获取可用的语音模型
  ipcMain.handle(MODEL_NAME + '/getGoogleAllVoices', async () => {
    return getGoogleAllVoices();
  });

  ipcMain.handle('tts/synthesize', (event, ...args) => {
    return synthesize(...args)
  })

  ipcMain.handle('tts/translate', (event, ...args) => {
    return textTranslate(...args)
  })

  ipcMain.handle('tts/batchTranslate', (event, ...args) => {
    return batchTextTranslate(...args)
  })

  ipcMain.handle('tts/synthesize_google_textToSpeech', (event, ...args) => {
    return synthesize_google_textToSpeech(...args)
  })

  // 获取可用的TTS模型列表
  ipcMain.handle('tts/getModels', async () => {
    try {
      return getAvailableTtsModels();
    } catch (error) {
      console.error('获取模型列表失败:', error);
      throw error;
    }
  });

  // 获取语音指令模板列表
  ipcMain.handle('tts/getInstructionTemplates', async () => {
    try {
      return getVoiceInstructionTemplates();
    } catch (error) {
      console.error('获取语音指令模板失败:', error);
      throw error;
    }
  });

  // 获取所有语言
  ipcMain.handle('tts/getSupportedLanguages', async () => {
    try {
      return getSupportedLanguages();
    } catch (error) {
      console.error('获取所有语言失败:', error);
      throw error;
    }
  });
}
